<template>
  <div class="carousel-management">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="轮播图标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入轮播图标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Plus" @click="handleAdd">新增轮播图</el-button>
          <el-button type="warning" @click="handleSortUpdate">更新排序</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column label="轮播图图片" width="180">
          <template #default="{ row }">
            <el-image
              :src="row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              fit="cover"
              style="width: 150px; height: 60px; border-radius: 4px"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="轮播图标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="link" label="跳转链接" min-width="200" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="100" sortable />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="160" />
        <el-table-column prop="endTime" label="结束时间" width="160" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleAction(command, row)">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="toggleStatus">
                    {{ row.status === 1 ? '禁用' : '启用' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <CarouselForm
      v-model:visible="dialogVisible"
      :mode="dialogMode"
      :data="currentCarousel"
      @success="handleFormSuccess"
    />

    <!-- 轮播图详情对话框 -->
    <CarouselDetail
      v-model:visible="detailVisible"
      :carousel-id="currentCarouselId"
      @edit="handleEditFromDetail"
    />

    <!-- 排序对话框 -->
    <el-dialog
      v-model="sortDialogVisible"
      title="轮播图排序"
      width="600px"
      @close="handleSortDialogClose"
    >
      <div class="sort-dialog-content">
        <p class="sort-tip">拖动调整轮播图显示顺序，点击保存后生效</p>
        <el-table
          :data="sortedTableData"
          row-key="id"
          style="width: 100%"
          @row-drop="handleRowDrop"
        >
          <el-table-column label="排序" width="80">
            <template #default="{ row }">
              <el-icon class="drag-handle"><Rank /></el-icon>
            </template>
          </el-table-column>
          <el-table-column label="标题" prop="title" />
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="图片" width="120">
            <template #default="{ row }">
              <el-image
                :src="row.imageUrl"
                fit="cover"
                style="width: 80px; height: 40px; border-radius: 4px"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleSortDialogClose">取消</el-button>
          <el-button type="primary" :loading="sortLoading" @click="handleSortSave">
            保存排序
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Picture, ArrowDown, Rank } from '@element-plus/icons-vue'
import { carouselAPI } from '@/api/banner'
import CarouselForm from './components/CarouselForm.vue'
import CarouselDetail from './components/CarouselDetail.vue'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const sortDialogVisible = ref(false)
const sortLoading = ref(false)
const sortedTableData = ref([])

const searchForm = reactive({
  title: '',
  status: null,
  dateRange: []
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const dialogVisible = ref(false)
const detailVisible = ref(false)
const dialogMode = ref('create')
const currentCarousel = ref(null)
const currentCarouselId = ref(null)

// 获取轮播图列表
const fetchCarouselList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      size: pagination.size,
      title: searchForm.title || undefined,
      status: searchForm.status !== null ? searchForm.status : undefined
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startTime = searchForm.dateRange[0]
      params.endTime = searchForm.dateRange[1]
    }

    const response = await carouselAPI.getList(params)
    tableData.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
    ElMessage.error('获取轮播图列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchCarouselList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    status: null,
    dateRange: []
  })
  pagination.current = 1
  fetchCarouselList()
}

// 新增轮播图
const handleAdd = () => {
  dialogMode.value = 'create'
  currentCarousel.value = null
  dialogVisible.value = true
}

// 查看详情
const handleViewDetail = (row) => {
  currentCarouselId.value = row.id
  detailVisible.value = true
}

// 编辑轮播图
const handleEdit = (row) => {
  dialogMode.value = 'edit'
  currentCarousel.value = { ...row }
  dialogVisible.value = true
}

// 处理操作
const handleAction = async (command, row) => {
  switch (command) {
    case 'toggleStatus':
      await handleToggleStatus(row)
      break
    case 'delete':
      await handleDelete(row)
      break
  }
}

// 切换状态
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'

  try {
    await ElMessageBox.confirm(
      `确定要${statusText}轮播图「${row.title}」吗？`,
      `${statusText}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await carouselAPI[newStatus === 1 ? 'enable' : 'disable'](row.id)
    ElMessage.success(`${statusText}成功`)
    fetchCarouselList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${statusText}轮播图失败:`, error)
      ElMessage.error(`${statusText}失败`)
    }
  }
}

// 删除轮播图
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除轮播图「${row.title}」吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await carouselAPI.delete(row.id)
    ElMessage.success('删除成功')
    fetchCarouselList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除轮播图失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 更新排序
const handleSortUpdate = () => {
  sortDialogVisible.value = true
  sortedTableData.value = [...tableData.value]
}

// 关闭排序对话框
const handleSortDialogClose = () => {
  sortDialogVisible.value = false
  sortedTableData.value = []
}

// 保存排序
const handleSortSave = async () => {
  sortLoading.value = true
  try {
    const sortArray = sortedTableData.value.map((item, index) => ({
      id: item.id,
      sort: index + 1
    }))

    await carouselAPI.updateSort({ sortArray })
    ElMessage.success('排序更新成功')
    sortDialogVisible.value = false
    fetchCarouselList()
  } catch (error) {
    console.error('更新排序失败:', error)
    ElMessage.error('更新排序失败')
  } finally {
    sortLoading.value = false
  }
}

// 拖拽排序
const handleRowDrop = (e) => {
  const targetRow = e.data
  const targetIndex = e.target.dataset.index * 1
  const sourceIndex = e.oldIndex * 1

  // 如果拖拽到无效位置，直接返回
  if (targetIndex === undefined || sourceIndex === undefined) return

  // 更新数组
  const newArray = [...sortedTableData.value]
  const [removed] = newArray.splice(sourceIndex - 1, 1)
  newArray.splice(targetIndex - 1, 0, removed)
  sortedTableData.value = newArray
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchCarouselList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  fetchCarouselList()
}

// 表单提交成功
const handleFormSuccess = () => {
  dialogVisible.value = false
  fetchCarouselList()
}

// 从详情页编辑轮播图
const handleEditFromDetail = (carousel) => {
  dialogMode.value = 'edit'
  currentCarousel.value = { ...carousel }
  dialogVisible.value = true
}

// 初始化
onMounted(() => {
  fetchCarouselList()
})
</script>

<style lang="scss" scoped>
.carousel-management {
  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .image-error {
      width: 150px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f5f7fa;
      border-radius: 4px;
      color: #c0c4cc;
    }

    .drag-handle {
      cursor: move;
      color: #909399;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }

  .sort-dialog-content {
    .sort-tip {
      color: #606266;
      margin-bottom: 20px;
      font-size: 14px;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>